'use strict'

const titbit = require('titbit')

const {cookie, session} = require('titbit-toolkit')

const app = new titbit({
  debug: true
})

app.use( (new cookie()).mid() )

//一定要在cookie之后，session是基于cookie的
app.use( (new session()).mid() )

app.use(async (c,next) => {
  console.log('just for home')
  await next()
  //添加只针对home分组执行的中间件
}, {group: 'home'})


app.get('/', async c => {
  c.res.body = 'success'
}, {name : '首页', group: 'home'})

app.get('/cookie', async c => {
  c.res.body = c.headers['cookie'] || '还没有设置cookie'
})

app.get('/login', async c => {
  c.res.body = `<!DOCTYPE html><html>
    <head>
      <meta charset="utf-8">
    </head>
    <body>
      <form action="/login" method="post">
        <input type="text" name="username">
        <input type="password" name="passwd">
        <input type="submit" value="Login">
      </form>
    </body>
  </html>`
})

app.post('/login', async c => {

  let {username, passwd} = c.body

  if (username === 'testuser' && passwd === '1234560') {
    c.setSession('is_login', true)
    //登录成功跳转到首页
    c.status(301)
    c.setHeader('Location', '/')
  } else {
    //登录失败跳转回登录页面
    c.status(301)
    c.setHeader('Location', '/login')
  }

})


app.run(1234)
